
package nachos.network;

import nachos.threads.*;

import java.util.ArrayList;

public class TimerThread {

   public static final int TICK_INTERVAL = 200000;

   //TODO: make this threadsafe!
   private ArrayList<TimerListener> listeners 
      = new ArrayList<TimerListener>();
   private static int i=0;
   private boolean shouldRun = true;
   private KThread thread = null;

   public TimerThread() {
      thread = new KThread( new TimerRunner(this) );
   }

   public void start() {
      thread.fork();
   }

   public void stop() {
      shouldRun = false;
   }

   private int currentTime() {
      return i += TICK_INTERVAL;
   }
   
   public int getCurrentTime()
   {
	   return i;
   }

   //TODO: make this threadsafe!
   private void notifyListeners() {
      for( int i=0; i<listeners.size(); i++ ) {
         listeners.get(i).handleTimer( currentTime() );
      }
   }

   //TODO: make this threadsafe!
   public void addListener( TimerListener listener ) {
      //System.out.println( "Adding " + listener + " to TimerListeners" );
      listeners.add( listener );
   }


   class TimerRunner implements Runnable {
      private TimerThread thread = null;
      public TimerRunner( TimerThread thread ) {
         this.thread = thread;
      }
      public void run() {
         while( true ) {
            thread.notifyListeners();
            ThreadedKernel.alarm.waitUntil( TICK_INTERVAL );
         }
      }
   }
}
